package org.me.runaway;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;


public class GPS extends MapActivity {

    private static final String GO_MAP_OPTION = "Mapa Principal";
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    private double fromLat = 0, fromLon = 0, toLat = 1, toLon = 1;
    Bundle extras;
    Intent intent;
    List<Overlay> mapOverlays;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        
        MapView.LayoutParams lp;
        lp = new MapView.LayoutParams(MapView.LayoutParams.WRAP_CONTENT, MapView.LayoutParams.WRAP_CONTENT, 10, 10, MapView.LayoutParams.TOP_LEFT);
        View zoomControls = mapView.getZoomControls();
        mapView.addView(zoomControls, lp);



        fromLat = StatusGPS.getMyPosition().getLatitudeE6() / 1E6;
        fromLon = StatusGPS.getMyPosition().getLongitudeE6() / 1E6;
        toLat = StatusGPS.getToPosition().getLatitudeE6() / 1E6;
        toLon = StatusGPS.getToPosition().getLongitudeE6() / 1E6;


        try {
            new Thread() {

                @Override
                public void run() {

                    String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
                    InputStream is = getConnection(url);
                    mRoad = RoadProvider.getRoute(is);
                    mHandler.sendEmptyMessage(0);

                }
            }.start();

        } catch (Exception e) {
            Toast.makeText(getBaseContext(), "Erro a tentar desenhar a rota",
                    Toast.LENGTH_LONG).show();
        }
    }
    Handler mHandler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            extras = getIntent().getExtras();
            if (extras != null) {
                textView.setText("Destino: " + extras.getString("name") + "\n" + mRoad.mDescription);
            } else {
                textView.setText(mRoad.mDescription);
            }

            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();

            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        }

        ;
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 0, 0, GO_MAP_OPTION).setIcon(R.drawable.world);
        menu.add(0, 1, 0, MainActivity.EXIT_OPTION).setIcon(R.drawable.logout);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 0:
                intent = new Intent(this, MainActivity.class);
                intent.putExtra("id", "myLocation");
                startActivity(intent);
                this.finish();
                return true;
            case 1:
                this.finish();
                return true;
        }

        return false;
    }


    class MapOverlay extends com.google.android.maps.Overlay {

        Road mRoad;
        ArrayList<GeoPoint> mPoints;

        MapOverlay() {
        }

        public MapOverlay(Road road, MapView mv) {
            mRoad = road;
            if (road.mRoute.length > 0) {
                mPoints = new ArrayList<GeoPoint>();

                for (int i = 0; i < road.mRoute.length; i++) {
                    mPoints.add(new GeoPoint((int) (road.mRoute[i][1] * 1000000),
                            (int) (road.mRoute[i][0] * 1000000)));
                }

                int moveToLat = (mPoints.get(0).getLatitudeE6() + (mPoints.get(
                        mPoints.size() - 1).getLatitudeE6() - mPoints.get(0).getLatitudeE6()) / 2);

                int moveToLong = (mPoints.get(0).getLongitudeE6() + (mPoints.get(
                        mPoints.size() - 1).getLongitudeE6() - mPoints.get(0).getLongitudeE6()) / 2);

                GeoPoint moveTo = new GeoPoint(moveToLat, moveToLong);

                MapController mapController = mv.getController();
                mapController.animateTo(moveTo);
                mapController.setZoom(13);


            }
        }

        @Override
        public boolean draw(Canvas canvas, MapView mv, boolean shadow, long when) {

            Paint paint = new Paint();
            super.draw(canvas, mv, shadow);

            Point screenPts = new Point();
            mapView.getProjection().toPixels(StatusGPS.getMyPosition(), screenPts);

            paint.setStrokeWidth(1);
            paint.setARGB(255, 255, 255, 255);
            paint.setStyle(Paint.Style.STROKE);
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.mylocation);
            canvas.drawBitmap(bmp, screenPts.x, screenPts.y, paint);

            mapView.getProjection().toPixels(StatusGPS.getToPosition(), screenPts);
            bmp = BitmapFactory.decodeResource(getResources(), R.drawable.goal);
            canvas.drawBitmap(bmp, screenPts.x, screenPts.y , paint);

            drawPath(mv, canvas);

            return true;
        }

        public void drawPath(MapView mv, Canvas canvas) {
            int x1 = -1, y1 = -1, x2 = -1, y2 = -1;
            Paint paint = new Paint();
            paint.setColor(Color.BLUE);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(3);
            for (int i = 0; i < mPoints.size(); i++) {
                Point point = new Point();
                mv.getProjection().toPixels(mPoints.get(i), point);
                x2 = point.x;
                y2 = point.y;
                if (i > 0) {
                    canvas.drawLine(x1, y1, x2, y2, paint);
                }
                x1 = x2;
                y1 = y2;
            }

        }
    }
}
